var app=getApp()
var util = require('../../../utils/util.js')
var api = require('../../../config/api.js')
var QQMapWX = require('../../../utils/qqmap-wx-jssdk'); // 引入 SDK 文件
var qqmapsdk; // SDK实例对象
Page({
  
  data: {
    // 
    toaddresslist:false,
// 用户地址列表
    useraddresslist:[],
    // 展示
    showaddress:true,
    // 存储用户的收货地址
    setaddressdata:{
      uuid:'',
      username:'',
      phone:'',
      address:'',
  },
    isShowAreaSelect: false,
    areaList: {
      // 变量名称是 van-area 规定写死的，不能换！不能换！不能换！
      province_list: {}, //省
      city_list: {},  //市
      county_list: {} //区
    },
    // 设置
    areaset:'',
  },
  onLoad(){
    // 获取地址
    util.request(api.ListUserAddress,{
      openid:wx.getStorageSync('token')
    },"POST").then(res=>{
      console.log(res)
      if(res.errno==0){
        let addresslist=res.data.addresslist;
        console.log(addresslist)
        this.setData({
          showaddress:false,
          useraddresslist:addresslist
        })
        wx.setStorageSync('addresslist', addresslist)
      }
    })
    
    
  },
  onShow(){
    let toaddresslist=wx.getStorageSync('toselectaddress');
    if(toaddresslist){
      this.setData({
        toaddresslist:true
      })
    }
    // this.onLoad();
    // 获取地址
    util.request(api.ListUserAddress,{
      openid:wx.getStorageSync('openid')
    },"POST").then(res=>{
      console.log(res)
      if(res.errno==0){
        let addresslist=res.data.addresslist;
        this.setData({
          showaddress:false,
          useraddresslist:addresslist
        })
        wx.setStorageSync('addresslist', addresslist)
      }
    })
    let avter=wx.getStorageSync('key')
    this.onReady()
  },
  onReady(){
    let addresslist=wx.getStorageSync('addresslist');
    console.log('addresslist:',addresslist)
    if(addresslist.length==0){
      this.setData({
        showaddress:true
      })
      this.attached()
    }else{
      this.setData({
        showaddress:false,
        useraddresslist:addresslist
      })
    }
  },
  // 加载数据
    attached() {
      //创建SDK实例
      qqmapsdk = new QQMapWX({
        key: 'OW7BZ-V43KK-LJQJX-AHYQQ-BCP26-ENF7U'
      });
      //调用 getCityList 
      qqmapsdk.getCityList({
        success: (res) => { //成功后的回调
          console.log('省份数据：', res.result[0][0]); //打印省份数据
          console.log('城市数据：', res.result[1][0]); //打印城市数据
          // console.log('区县数据：', res.result[2]); //打印区县数据
          this.setData({
            "areaList.province_list": this.ArrayToObject(res.result[0]),
            "areaList.city_list": this.ArrayToObject(res.result[1]),
            "areaList.county_list": this.ArrayToObject(res.result[2]),
          })
        },
        fail: function (error) {
          console.error(error);
        },
        complete: function (res) {
          console.log(res);
        }
      });
    },
    //确认选择
    confirmArea(e) {
      const values = e.detail.values
      console.log('values:',values)
      //直辖市，需要处理数据，保持省市一致，例如，省：北京市；市：北京市；区：朝阳区
      if (values.some(x => !Boolean(x)))[values[1], values[2]] = [values[0], values[1]];
      const arr = (values.map(x => x.name))
      //调用父组件的传递方法，并传递选择结果。
      console.log('arr:',arr)
      // 设置地址
      let areas=''
      arr.forEach((item,index) => {
        // console.log(item)
        areas+=item
      });
      console.log(areas)
      this.triggerEvent("confirm", arr)
      this.setData({
        areaset:areas,
        isShowAreaSelect: false,
      })
    },

    //关闭省市区选择组件
    closeAreaSelect() {
      this.setData({
        isShowAreaSelect: false
      })
    },

    //打开省市区选择组件
    showAreaSelect() {
      this.setData({
        isShowAreaSelect: true
      })
    },

   // 格式化省市区数据
    ArrayToObject(arr) {
      const obj = {}
      for (let i = 0; i < arr.length; i++) {
        obj[arr[i].id] = arr[i].fullname
      }
      return obj
    },
    // 选择所在地
    addarea(){
      this.showAreaSelect()
    },
    // 提交
    saveaddress(){
      let that=this;
      // 新添加的
      let useraddress=this.data.setaddressdata;
      // 原来的
      let address=this.data.useraddresslist;

      console.log('useraddress:',useraddress)
      address.push(useraddress)
      // console.log('address:',address)
      // this.setData({
      //   useraddresslist:address,
      //   username:'',
      //   phone:'',
      //   areaset:'',
      //   xiangxi:''
      // })
      // wx.setStorageSync('addresslist', address)
      // 将地址添加到后台
      // util.request(api.AddressSave,{
        console.log(wx.getStorageSync('userInfo').avatarUrl)
        util.request(api.AddUserAddress,{
        avatar:wx.getStorageSync('userInfo').avatar,
        openid:wx.getStorageSync('openid'),
        token:wx.getStorageSync('token'),
        addresslist:useraddress
      },"POST").then(res=>{
        console.log('res')
        util.request(api.ListUserAddress,{
          openid:wx.getStorageSync('token')
        },"POST").then(res=>{
          console.log(res)
          if(res.errno==0){
            console.log(res.data)
            let addresslist=res.data.addresslist;
            this.setData({
              showaddress:false,
              useraddresslist:addresslist
            })
            wx.showToast({
              title:'',
              duration: 2000, //延时时间长一点好截图
              complete:res=>{
                setTimeout(function () {
                  //要延时执行的代码
                  that.onLoad()
                  that.onShow()
                  that.onReady()
                  wx.setStorageSync('addresslist', addresslist)
                }, 1000) //延迟时间
              }
            })
            
            
            
          }
        })

      })

      // wx.navigateTo({
      //   url: '/pages/me/address/address',
      // })
      // this.onLoad()
      // this.onShow()
      this.onReady()
    },
    onChange(e){
      console.log('e:',e)
    },
    // 获取用户名
    nameinput(e){
      let username='setaddressdata.username'
      let name=e.detail.value
      this.setData({
        [username]:name
      })
    },
    // 获取手机号
    phoneinput(e){
      let setphone='setaddressdata.phone'
      let phone=e.detail.value
      this.setData({
        [setphone]:phone
      })
    },
    // 获取所在地
    addareainput(e){
      var addresstemp=e.detail.value
      this.setData({
        areaset:addresstemp
      })
    },
    // 详细地址
    xiangxiinput(e){
      let addresstemp=e.detail.value
      let address= this.data.areaset+addresstemp
      let uuid='setaddressdata.uuid'
      let wxuuid=util.wxuuid();
      let setaddress='setaddressdata.address'
      this.setData({
        [setaddress]:address,
        [uuid]:wxuuid
      })
    },
    // x修改地址
    addressedit(e){
      let id=e.currentTarget.dataset.id;
      console.log(e)
      wx.navigateTo({
        url: '/pages/me/editaddress/editaddress?id='+id,
      })
    },
    // 添加地址
    addaddress(){
      this.setData({
        showaddress:true
      })
      // 获取数据
      this.attached();
    },
    // 
    onClose(event) {
      const { position, instance } = event.detail;
      switch (position) {
        case 'left':
        case 'cell':
          instance.close();
          break;
        case 'right':
          Dialog.confirm({
            message: '确定删除吗？',
          }).then(() => {
            instance.close();
          });
          break;
      }
    },
    // 选择地址
    toselect(e){
      let id=e.currentTarget.dataset.id;
      let selectaddress=this.data.useraddresslist.map(item=>{
        if(item.id==id){
          return item
        }
      });
      selectaddress=selectaddress.filter(item=>item);
      wx.setStorageSync('selectaddress', selectaddress)
      wx.navigateBack({
        delta: 1,
      })
    }
})